package org.example.interceptor;

import org.example.service.RedisRateLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class RateLimitInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisRateLimiter redisRateLimiter;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 这里以客户端 IP 作为限流标识，也可以根据接口 URL、用户ID等来做区分
        String clientIP = request.getRemoteAddr();
        String key = "rate:" + clientIP;
        // 设置限流阈值，例如每60秒最多允许 5 次请求
        int limit = 5;
        int windowSeconds = 60;

        boolean allowed = redisRateLimiter.isAllowed(key, limit, windowSeconds);
        if (!allowed) {
            //设置返回的响应内容为json
            response.setContentType("application/json;charset=UTF-8");
            // 超出限流，返回 429 状态码（Too Many Requests）
            response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
            response.getWriter().write("Too Many Requests - 接口访问过于频繁");
            return false;
        }
        return true;
    }
}
